import axios from 'axios'
import store from '../store/index'

let cancel = {}
let promiseArr = {}
const CancelToken = axios.CancelToken
//  请求拦截器
axios.interceptors.request.use(config => {
    //  发起请求时，取消掉当前正在进行的相同请求
    if (promiseArr[config.url]) {
        promiseArr[config.url]('操作取消')
        promiseArr[config.url] = cancel
    } else {
        promiseArr[config.url] = cancel
    }
    store.commit('showloader')
    return config
}, error => {
    return Promise.reject(error)
})

//  响应拦截器即异常处理
axios.interceptors.response.use(response => {
  store.commit('hideloader')
  if (response.data['business'] === 'noLogin') {
    store.commit('setLoginState', false)
  }
  return response
}, err => {
    if (err && err.response) {
        err.data = {
          message: '连接到服务器失败',
          result: 'error'
        }
    }
    store.commit('hideloader')
    return Promise.resolve(err)
})

axios.defaults.baseURL = '/ect'
//  设置默认请求头
// axios.defaults.headers = {
//     'Content-Type': 'application/json;charset=UTF-8'
// }
axios.defaults.timeout = 50000

export default {
    //  get请求
    get(url, param) {
        return new Promise((resolve, reject) => {
            axios({
                method: 'get',
                url,
                params: param,
                cancelToken: new CancelToken(c => {
                    cancel = c
                })
            }).then(res => {
                resolve(res)
            })
        })
    },
    //  post请求
    post(url, param) {
        return new Promise((resolve, reject) => {
            axios({
                method: 'post',
                url: url,
                data: param,
                cancelToken: new CancelToken(c => {
                    cancel = c
                })
            }).then(res => {
                resolve(res)
            })
        })
    },
    //  delete请求
    delete(url, param) {
      return new Promise((resolve, reject) => {
        axios({
          method: 'delete',
          url: url,
          params: param,
          cancelToken: new CancelToken(c => {
            cancel = c
          })
        }).then(res => {
          resolve(res)
        })
      })
    }
}
